package jwt

import (
	"dc-news-admin-api/common/global/consts"
	"dc-news-admin-api/common/resp"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Auth(role string) gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("Authorization")
		if token == "" {
			c.JSON(http.StatusUnauthorized, resp.NewErrResp(consts.TokenErrorCode, "token错误！"))
			c.Abort()
			return
		}
		j := NewJWT()
		// parseToken 解析token包含的信息
		claims, err := j.ParseToken(token)
		if err != nil {
			c.JSON(http.StatusUnauthorized, resp.NewErrResp(consts.TokenErrorCode, err.Error()))
			c.Abort()
			return
		}
		switch claims.Role {
		case "su":
			break
		case "admin":
			if role == "su" {
				c.JSON(http.StatusUnauthorized, resp.NewErrResp(consts.TokenErrorCode, "权限不足"))
				c.Abort()
				return
			}
		case "editor":
			if role != "editor" {
				c.JSON(http.StatusUnauthorized, resp.NewErrResp(consts.TokenErrorCode, "权限不足"))
				c.Abort()
				return
			}
		default:
			c.JSON(http.StatusUnauthorized, resp.NewErrResp(consts.TokenErrorCode, "token错误"))
			c.Abort()
			return
		}
		// 继续交由下一个路由处理,并将解析出的信息传递下去
		c.Set("claims", claims)
	}
}
